package com.budwk.app.sqfwV2.service.weiqingmen;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.dto.PeopleTagDTO;
import com.budwk.app.sqfw.dto.PersonnelTagDTO;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.PersonInfo;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.PersonInfoService;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BasePdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService.CompleteFlowCommonPdfService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.result.GeneratorPdfWordResult;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.component.SummarySafetyCommponent;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.dto.weiqingmen.HouseHoldSurveyDTO;
import com.budwk.app.sqfwV2.dto.weiqingmen.InterviewDTO;
import com.budwk.app.sqfwV2.enums.weiqingmen.HouseHoldSurveyEnum;
import com.budwk.app.sqfwV2.generator.weiqingmen.BaseGenerator;
import com.budwk.app.sqfwV2.generator.weiqingmen.survey.PersonnelInspectionPdfGenerator;
import com.budwk.app.sqfwV2.service.SummarySafetyService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.generateWordDocument;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-08-02
 *
 * 威清路入户调查 HouseHoldSurvey
 */
@IocBean
@Slf4j
public class HouseHoldSurveyPdfService extends CompleteFlowCommonPdfService{

    @Inject
    private SummarySafetyCommponent summarySafetyCommponent;
    @Inject
    SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    SysUserService sysUserService;
    @Inject
    private SummarySafetyService summarySafetyService;
    @Inject
    private PersonInfoService personInfoService;
    @Inject
    private SysDictService dictService;

    /**
     * 新增
     * @param dto
     */
    public void submitData(TemplateCodeUpdateDTO dto) {
        log.info("威清门入户调查：{}", JSONUtil.toJsonStr(dto));
        CompleteFlowPdfParamForController paramForController = new CompleteFlowPdfParamForController();
        CompleteFlowTemplateCodeUpdateDTO completeFlowDataDTO = new CompleteFlowTemplateCodeUpdateDTO();

        // 设置上访时间
        Sqfw_formSummary_new formSummary = dto.getFormSummary();
        HouseHoldSurveyDTO holdSurveyDTO = JSONUtil.toBean(formSummary.getParamData(), HouseHoldSurveyDTO.class);
        Date fillDate = null;
        List<InterviewDTO> interviewDTOList = holdSurveyDTO.getInterviewDTOList();
        for (InterviewDTO interviewDTO : interviewDTOList) {
            if (fillDate == null) {
                fillDate = interviewDTO.getFillDate();
            } else if (DateUtil.compare(fillDate, interviewDTO.getFillDate()) < 0) {
                fillDate = interviewDTO.getFillDate();
            }
        }
        formSummary.setFillDate(fillDate);

        // 添加人员标签
        List<String> careCategory = holdSurveyDTO.getCareCategory();
        List<PeopleTagDTO> specialMark = new ArrayList<>();
        PeopleTagDTO tagDTO = new PeopleTagDTO();
        tagDTO.setBusinessType(getSummaryType());
        tagDTO.setCode(SupportBusinessTypeEnum.HOUSE_SURVEY_FORM.getCode());
        List<PeopleTagDTO.Dict> tag = new ArrayList<>();
        for (String v : careCategory) {
            PeopleTagDTO.Dict dict = new PeopleTagDTO.Dict();
            dict.setBusinessType("走访人员类别");
            dict.setName(v);
            dict.setKey(dictService.getCode("weiqingmen_survey_personnel_category", v));
            tag.add(dict);
        }
        tagDTO.setTag(tag);
        specialMark.add(tagDTO);
        PersonInfo personInfo = personInfoService.fetch(holdSurveyDTO.getId());
        if (personInfo == null) throw new ServiceException("人员信息不存在");
        personInfo.setSpecialMark(JSONUtil.toList(JSONUtil.toJsonStr(specialMark), PersonnelTagDTO.class));
        personInfoService.updateIgnoreNull(personInfo);

        completeFlowDataDTO.setFormSummary(formSummary);
        completeFlowDataDTO.setCompleteFlow(dto.getCompleteFlow());
        paramForController.setCompleteFlowDataDTO(completeFlowDataDTO);
        paramForController.setUserId(SecurityUtil.getUserId());
        // 创建任务
        summarySafetyCommponent.createOneTask(dto, null, getSummaryType());
        // 创建pdf
        super.createPdfAndMsg(paramForController);
    }

    /**
     * 更新 2.0版本
     * @param dto
     */
    public void update(TemplateCodeUpdateDTO dto) {
        log.info("威清门入户调查更新：{}", JSONUtil.toJsonStr(dto));

        sqfwFormsummaryNewService.updateIgnoreNull(dto.getFormSummary());
        Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(dto.getFormSummary().getId());
        CompleteFlowPdfParamForController paramForController = new CompleteFlowPdfParamForController();
        CompleteFlowTemplateCodeUpdateDTO updateDTO = new CompleteFlowTemplateCodeUpdateDTO();

        // 设置上访时间
        Sqfw_formSummary_new formSummary = dto.getFormSummary();
        HouseHoldSurveyDTO holdSurveyDTO = JSONUtil.toBean(formSummary.getParamData(), HouseHoldSurveyDTO.class);
        Date fillDate = null;
        List<InterviewDTO> interviewDTOList = holdSurveyDTO.getInterviewDTOList();
        for (InterviewDTO interviewDTO : interviewDTOList) {
            if (fillDate == null) {
                fillDate = interviewDTO.getFillDate();
            } else if (DateUtil.compare(fillDate, interviewDTO.getFillDate()) < 0) {
                fillDate = interviewDTO.getFillDate();
            }
        }
        formSummary.setFillDate(fillDate);

        // 更新人员标签
        List<String> careCategory = holdSurveyDTO.getCareCategory();
        List<PeopleTagDTO> specialMark = new ArrayList<>();
        PeopleTagDTO tagDTO = new PeopleTagDTO();
        tagDTO.setBusinessType(getSummaryType());
        tagDTO.setCode(SupportBusinessTypeEnum.HOUSE_SURVEY_FORM.getCode());
        List<PeopleTagDTO.Dict> tag = new ArrayList<>();
        for (String v : careCategory) {
            PeopleTagDTO.Dict dict = new PeopleTagDTO.Dict();
            dict.setBusinessType("走访人员类别");
            dict.setName(v);
            dict.setKey(dictService.getCode("weiqingmen_survey_personnel_category", v));
            tag.add(dict);
        }
        tagDTO.setTag(tag);
        specialMark.add(tagDTO);
        PersonInfo personInfo = personInfoService.fetch(holdSurveyDTO.getId());
        if (personInfo == null) throw new ServiceException("人员信息不存在");
        personInfo.setSpecialMark(JSONUtil.toList(JSONUtil.toJsonStr(specialMark), PersonnelTagDTO.class));
        personInfoService.updateIgnoreNull(personInfo);

        updateDTO.setFormSummary(formSummaryNew);
        paramForController.setCompleteFlowDataDTO(updateDTO);
        paramForController.setCompleteFlowId(formSummaryNew.getSqfwFlowId());
        paramForController.setUserId(SecurityUtil.getUserId());
        super.reCreatePdfAndMsg(paramForController);
    }

    /**
     * 根据completeFlowId重新生成pdf
     *
     * @param completeFlowId
     */
    public void reCreatePdfAndMsg(String completeFlowId) {
        CompleteFlowPdfParamForController paramForController = new CompleteFlowPdfParamForController();
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getSqfwFlowId, "=", completeFlowId);
        Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(cnd);
        if (formSummaryNew == null) {
            throw new RuntimeException("数据不存在");
        }
        paramForController.setUserId(formSummaryNew.getCreateBy());
        paramForController.setCompleteFlowId(completeFlowId);
        super.reCreatePdfAndMsg(paramForController);
    }

    /**
     * 获取人员最新一条巡查记录
     * @param personId
     * @return
     */
    public Sqfw_formSummary_new getLatest(String personId) {
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getType, "=", this.getSummaryType());
        cnd.and("param_data->>'id'", "=", personId);
        cnd.desc(Sqfw_formSummary_new::getFillDate);
        return sqfwFormsummaryNewService.fetch(cnd);
    }

    /**
     * 获取列表数据 2.0版本
     * @return
     */
    public Result<?> list(Integer pageNo, Integer pageSize, String fillDate, String sort, String id, String careCategory) {
        SummaryQueryReqVo dto = new SummaryQueryReqVo();
        dto.setPageNo(pageNo);
        dto.setPageSize(pageSize);
        dto.setSort(sort);
        dto.setFillDate(fillDate);
        dto.setFillType(getSummaryType());

        if (StringUtils.isNotBlank(id) || StringUtils.isNotBlank(careCategory)) {
            SqlExpressionGroup sqlExpressionGroup = new SqlExpressionGroup();
            if (StringUtils.isNotBlank(id)) {
                sqlExpressionGroup.and("param_data->>'id'", "=", id);
            }
            if (StringUtils.isNotBlank(careCategory) && !"全选".equalsIgnoreCase(careCategory)) {
                SqlExpressionGroup expressionGroup = new SqlExpressionGroup();
                String careCategoryList[] = careCategory.split(",");
                int i = 0;
                for (String v : careCategoryList) {
                    if (i == 0) {
                        expressionGroup.and("param_data->'careCategory'", "@>", "[\""+v+"\"]");
                    } else {
                        expressionGroup.or("param_data->'careCategory'", "@>", "[\""+v+"\"]");
                    }

                }
                sqlExpressionGroup.and(expressionGroup);
            }

            dto.setSqlExpressionGroup(sqlExpressionGroup);
        }

        return summarySafetyService.listSummaryByPage(dto);
    }

    /**
     * pdf合集下载（通过sqfwIdList下载pdf合集）2.0版本 app端
     *
     * @param reqVo
     * @return
     */
    public List<ResultOfExcelGenerator> downPdfList(DownExcelLedgerReqVo reqVo) {
        List<ExcelCreateConfig> excelConfigList = new ArrayList<>();
        if (reqVo.isDownTemplate()) {
            ExcelCreateConfig config = new ExcelCreateConfig();
            config.setFileIdentity(reqVo.getFileCode());
            config.setOnlyGenerateTemplateFlag(true);
            excelConfigList.add(config);
        } else {
            Map<String,Object> param = new HashMap<>();
            param.put("start", reqVo.getFillStartDate());
            param.put("end", reqVo.getFillEndDate());
            param.put("personInfoId", reqVo.getQueryKey());
            if (reqVo.isCheckData()) {
                for (HouseHoldSurveyEnum pdf : HouseHoldSurveyEnum.getPdf()) {
                    ExcelCreateConfig config = new ExcelCreateConfig();
                    config.setFileIdentity(pdf.getCode());
                    config.setCreateExcelFileFlag(false);
                    config.setParam(param);
                    excelConfigList.add(config);
                }
            } else {
                ExcelCreateConfig config = new ExcelCreateConfig();
                config.setFileIdentity(reqVo.getFileCode());
                config.setCreateExcelFileFlag(true);
                config.setParam(param);
                excelConfigList.add(config);
            }
        }
        return downPdfList(excelConfigList, null);
    }

    /**
     * pdf合集下载（通过sqfwIdList下载pdf合集）
     *
     * @param excelConfigList
     * @return
     */
    public List<ResultOfExcelGenerator> downPdfList(List<ExcelCreateConfig> excelConfigList, List<String> summaryIds) {

        List<ResultOfExcelGenerator> generateExcelUrlVOS = new ArrayList<>();

        List<Sqfw_completeflow> completeFlowList = null;

        ExcelCreateConfig config0 = excelConfigList.get(0);

        if (!config0.getOnlyGenerateTemplateFlag()) {
            if (summaryIds == null || summaryIds.size() == 0) {
                String sql = "select sc.resource_path from shequ.sqfw_completeflow sc left join shequ.sqfw_form_summary_new sfsn " +
                        "on sc.id = sfsn.sqfw_flow_id where " +
                        "sfsn.create_by ='" + SecurityUtil.getUserId() + "' and sfsn.type = '" + this.getSummaryType() +
                        "' and sc.resource_path != 'error' and sc.resource_path != 'creating' ";
                if (config0.getParam().get("start") != null && StringUtils.isNotBlank(config0.getParam().get("start").toString())) {
                    sql += " and fill_date >= '" + config0.getParam().get("start").toString() + "'";
                }
                if (config0.getParam().get("end") != null && StringUtils.isNotBlank(config0.getParam().get("end").toString())) {
                    sql += " and fill_date <= '" + config0.getParam().get("end").toString() + " 23:59:59'";
                }
                if (config0.getParam().get("personInfoId") != null && StringUtils.isNotBlank(config0.getParam().get("personInfoId").toString())) {
                    sql += " and param_data->>'id' = '" + config0.getParam().get("personInfoId").toString() + "'";
                }
                sql += " order by fill_date asc";
                completeFlowList = sqfwCompleteflowService.listEntity(Sqls.create(sql));
            } else {
                String sql = "select sc.resource_path from shequ.sqfw_completeflow sc left join shequ.sqfw_form_summary_new sfsn " +
                        "on sc.id = sfsn.sqfw_flow_id where " +
                        "sfsn.id in" + StrUtil.formatIds(summaryIds) +
                        "and sc.resource_path != 'error' and sc.resource_path != 'creating' ";
                sql += "order by fill_date asc";
                completeFlowList = sqfwCompleteflowService.listEntity(Sqls.create(sql));
            }
        }

        for (ExcelCreateConfig config : excelConfigList) {

            // 模板下载
            if (config.getOnlyGenerateTemplateFlag()) {
                ResultOfExcelGenerator generateExcelUrlVO = new ResultOfExcelGenerator();
                String url = downWordTemplate(config);
                generateExcelUrlVO.setExcelUrl(url);
                generateExcelUrlVOS.add(generateExcelUrlVO);
                continue;
            }

            ResultOfExcelGenerator generateExcelUrlVO = new ResultOfExcelGenerator();
            generateExcelUrlVO.setFileIdentity(config.getFileIdentity());

            if (completeFlowList != null && completeFlowList.size() > 0) {
                generateExcelUrlVO.setPassCreateConditionFlag(true);
            } else {
                generateExcelUrlVO.setPassCreateConditionFlag(false);
            }

            // 数据检测
            if (!config.getCreateExcelFileFlag() || completeFlowList == null || completeFlowList.size() == 0) {
                generateExcelUrlVOS.add(generateExcelUrlVO);
                continue;
            }

            List<String> pdfList = completeFlowList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());

            // 下载 pdf
            try {
                String fileName = HouseHoldSurveyEnum.getCompilationName(config.getFileIdentity());
                fileName = StrFormatter.format("{}-{}", fileName, DateUtil.format(new Date(), "yyyyMMdd"));
                String url = CommonFormOfficeUtils.createConvergePdf(pdfList, fileName);
                url = (url.startsWith("/")) ? NutzIocUtils.getOssPrefix() + url : url;
                generateExcelUrlVO.setExcelUrl(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            generateExcelUrlVOS.add(generateExcelUrlVO);
        }

        return generateExcelUrlVOS;
    }

    @Override
    public void reCreatePdfAndMsg(CompleteFlowPdfParamForController paramForController) {
        super.reCreatePdfAndMsg(paramForController);
    }

    @Override
    public GeneratorPdfWordResult createPdfSync(CompleteFlowPdfParamForController paramForController) {
        return super.createPdfSync(paramForController);
    }

    /**
     * 获取用户自定义字段 代码生成器已经自动填充
     * 无需特殊修改
     *
     * @param paramData json字符串
     * @return 结果
     */
    @Override
    protected AbstractCustomerPdfCreateField getCustomerPdfField(String paramData) {
        return JSONObject.parseObject(paramData, HouseHoldSurveyDTO.class);
    }

    /**
     * 允许用户自定义填充在创建pdf时所提供的数据
     *
     * @param pdfGenerateParam 创建pdf所提供的数据
     */
    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam) {

    }

    /**
     * 在这里设置生成pdf的所有generator
     *
     * @param pdfGenerateParam 创建pdf的参数
     * @return 生成pdf的generator合集
     */
    @Override
    protected List<BasePdfGenerator> getPdfGenerator(PdfGenerateParam pdfGenerateParam) {
        List<BasePdfGenerator> generatorList = Lists.newArrayList();
        // 在这里添加自己的generator
        // 例如 generatorList.add(new RefuseClassifyPdfGenerator());
        generatorList.add(new PersonnelInspectionPdfGenerator());
        return generatorList;
    }

    /**
     * 用户自定义下载pdf文件的名称
     *
     * @param pdfGenerateParam 创建pdf所提供的参数
     * @return 结果
     */
    @Override
    protected String getDownloadFileName(PdfGenerateParam pdfGenerateParam) {
        return HouseHoldSurveyEnum.PERSONNEL_INSPECTION.getOneName();
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    public String getSummaryType() {
        return SqfwFormSummaryConstants.house_survey_form;
    }

    /**
     * 下载word模板
     *
     * @param config
     * @return
     */
    private String downWordTemplate(ExcelCreateConfig config) {
        String fileName = HouseHoldSurveyEnum.getTemplateName(config.getFileIdentity());

        List<NiceXWPFDocument> xwpfDocumentList = new ArrayList<>();

        // pdf模板
        if (HouseHoldSurveyEnum.PERSONNEL_INSPECTION.getCode().equals(config.getFileIdentity())) {
            // 人员巡查
            xwpfDocumentList.add(getNiceXWPFDocument(new PersonnelInspectionPdfGenerator().getTemplatePath(null)));

            GenerateWordAndPdfUrlVO vo = CommonFormOfficeUtils.wordTemplateUpload(xwpfDocumentList, fileName);
            return vo.getWordUrl();
        }

        return null;
    }

    /**
     * 生成单个word
     *
     * @param templateName
     * @return
     */
    public NiceXWPFDocument getNiceXWPFDocument(String templateName) {
        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());

        // 获取模板里 文本编辑、图片标签、表达式标签
        Map<String, Object> dataMap = CommonFormOfficeUtils.getWordTag(templateName);

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, BaseGenerator.getFooter(user), templateName);
        return xwpfTemplate.getXWPFDocument();
    }

    /**
     * 添加人员信息
     * @param personInfo
     * @return
     */
    public Result<?> addPersonInfo(PersonInfo personInfo) {
        Sys_user sysUser = sysUserService.getUserById(SecurityUtil.getUserId());

        Cnd cnd = Cnd.NEW();
        cnd.and(PersonInfo::getName, "=", personInfo.getName());
        cnd.and(PersonInfo::getCommunity, "=", sysUser.getCommunity());
        cnd.and(PersonInfo::getAddress, "=", personInfo.getAddress());
        PersonInfo person = personInfoService.fetch(cnd);
        if (person != null) return Result.success("该人员已存在");

        personInfo.setBusinessType(this.getSummaryType());
        personInfo.setUnitName(sysUser.getUnitName());
        personInfo.setProvince(sysUser.getProvince());
        personInfo.setCity(sysUser.getCity());
        personInfo.setDistrict(sysUser.getDistrict());
        personInfo.setCounty(sysUser.getCounty());
        personInfo.setCommunity(sysUser.getCommunity());
        personInfo.setCreateBy(sysUser.getId());
        personInfo.setCreateDate(LocalDateTime.now());
        personInfo.setAge(DateUtil.ageOfNow(new DateTime(personInfo.getBirthDate())));
        return Result.data(personInfoService.insert(personInfo));
    }

    /**
     * 更新人员信息
     * @param personInfo
     * @return
     */
    public Result<?> updatePersonInfo(PersonInfo personInfo) {
        Sys_user sysUser = sysUserService.getUserById(SecurityUtil.getUserId());

        Cnd cnd = Cnd.NEW();
        cnd.and(PersonInfo::getId, "!=", personInfo.getId());
        cnd.and(PersonInfo::getName, "=", personInfo.getName());
        cnd.and(PersonInfo::getCommunity, "=", sysUser.getCommunity());
        cnd.and(PersonInfo::getAddress, "=", personInfo.getAddress());
        PersonInfo person = personInfoService.fetch(cnd);
        if (person != null) return Result.success("该人员已存在");

        personInfo.setUpdateBy(SecurityUtil.getUserId());
        personInfo.setUpdateDate(LocalDateTime.now());
        personInfo.setAge(DateUtil.ageOfNow(new DateTime(personInfo.getBirthDate())));
        return Result.data(personInfoService.updateIgnoreNull(personInfo));
    }

    /**
     * 获取人员列表
     * @param pageNo
     * @param pageSize
     * @param query
     * @param category
     * @return
     */
    public Pagination pagePersonInfo(Integer pageNo, Integer pageSize, String query, String category) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select * from shequ.sqfw_person_info where ");
        stringBuilder.append("business_type like '%");
        stringBuilder.append(this.getSummaryType()).append("%'");
        // 设置5级区域查询
        String five = CommonCheckUtils.getLv5();
        if (StringUtils.isNotBlank(five)) {
            stringBuilder.append(five);
        }
        if (StringUtils.isNotBlank(query)) {
            stringBuilder.append(" and ");
            stringBuilder.append("(name like '%"+query+"%' or id_number like '%"+query+"%')");
        }
        if (StringUtils.isNotBlank(category)) {
            stringBuilder.append(" and ");
            stringBuilder.append("EXISTS (SELECT 1 FROM jsonb_array_elements(special_mark::jsonb) AS elem WHERE elem->>'businessType' ='");
            stringBuilder.append(this.getSummaryType()).append("'");
            stringBuilder.append("and elem->'tag' @> '");
            String categoryList[] = category.split(",");
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (String s : categoryList) {
                mapList.add(Map.of("name", s));
            }
            stringBuilder.append(JSONUtil.toJsonStr(mapList));
            stringBuilder.append("')");
        }
        stringBuilder.append(" order by create_date desc");
        Pagination pagination = personInfoService.listPageEntity(pageNo, pageSize, Sqls.create(stringBuilder.toString()));
        return pagination;
    }
}
